<template>
  <div class="user-info">
    <div class="signatureBox-popup" :style="{ 'z-index': zIndex }">
      <div class="popup2">
        <div class="signatureBox">
          <div class="canvasBox" ref="canvasHW">
            <div style="padding-top: 20px" class="input_text">
              请在下面空白区域签名
            </div>
            <div
              style="padding-top: 10px; color: #ff0045; font-size: 12px"
              class="input_text"
            >
              必须由本人签字，违者将承担法律责任
            </div>
            <canvas
              ref="canvasF"
              @touchstart="touchStart"
              @touchmove="touchMove"
              @touchend="touchEnd"
              @mousedown="mouseDown"
              @mousemove="mouseMove"
              @mouseup="mouseUp"
            ></canvas>
            <div class="btnBox">
              <!-- <div @click="overwrite">重写</div> -->
              <!-- <div @click="commit">提交签名</div> -->
            </div>
          </div>
        </div>
        <div style="padding-bottom: 20px; background-color: #fff">
          <button
            style="
              border: none;
              border-radius: 20px;
              color: #fff;
              padding: 5px;
              margin-left: 20px;
              float: left;
              background: #0798ea;
              width: 23%;
            "
            @click="commit"
          >
            确定
          </button>
          <button
            style="
              border: none;
              border-radius: 20px;
              color: #fff;
              padding: 5px;
              background: #b9bfd3;
              width: 23%;
            "
            @click="overwrite"
          >
            清除
          </button>
          <button
            style="
              border: none;
              border-radius: 20px;
              color: #fff;
              padding: 5px;
              margin-right: 20px;
              float: right;
              background: #b9bfd3;
              width: 23%;
            "
            @click="Canvas_goBack"
          >
            取消
          </button>
        </div>
      </div>
    </div>

    <div class="read-pdf">
      <pdf ref="pdf" v-for="i in numPages" :key="i" :src="url" :page="i"></pdf>
    </div>
    <van-button
      class="button-fixed"
      type="info"
      block
      @click="submit"
      v-if="isSignatureBool"
    >
      签字
    </van-button>
  </div>
</template>

<script>
import pdf from "vue-pdf";
import {
  CommonAttachUploadBase64,
  SiteAppointmentSign,
  SitePromiseRecordSign,
  SiteSafeCostPlanMainSign,
} from "@/api/common";
import { mapGetters } from "vuex";
export default {
  components: {
    pdf,
  },
  data() {
    return {
      adds: "",
      zIndex: -8,
      isCertificate: true,
      isCertificate2: false,
      stageInfo: "",
      client: {},
      points: [],
      canvasTxt: null,
      startX: 0,
      startY: 0,
      moveY: 0,
      moveX: 0,
      endY: 0,
      endX: 0,
      w: null,
      h: null,
      isDown: false,
      isViewAutograph: this.$route.query.isViews > 0,
      contractSuccess: this.$route.query.contractSuccess,

      url: ``,
      numPages: 0, // pdf 总页数
      TypeName: null,
      isSignature: null,
      isSignatureBool: false,
      id: this.$route.query.IDS,
      DocCode: this.$route.query.DocCode,
    };
  },
  created() {
    this.$toast.loading({
      message: "加载中...",
      forbidClick: true,
    });
  },

  computed: {
    ...mapGetters(["baseUrl", "CompanyCode", "roles"]),
  },

  mounted() {
    this.url = this.$route.query.url;
    this.TypeName = this.$route.query.TypeName;
    this.isSignature = this.$route.query.isSignature;
    this.id = this.$route.query.IDS;
    this.DocCode = this.$route.query.DocCode;
    if (
      this.isSignature == "isSignature" ||
      this.isSignature == "forSignature" ||
      this.isSignature == "ProjectEntrustedOnlineDoc" ||
      this.isSignature == "SitePromiseRecordSign" ||
      this.isSignature == "SiteSafeCostPlanMain" ||
      this.isSignature == "ResponsibilityOrgPostUserDepositManage"
    ) {
      this.isSignatureBool = true;

      let canvas = this.$refs.canvasF;
      canvas.height = this.$refs.canvasHW.offsetHeight - 500;
      canvas.width = this.$refs.canvasHW.offsetWidth - 50;
      this.canvasTxt = canvas.getContext("2d");
      this.stageInfo = canvas.getBoundingClientRect();
    }
    console.log("http======id==>" + this.TypeName);
    console.log("http======isSignature==>" + this.isSignature);
    console.log("http======isSignatureBool==>" + this.isSignatureBool);
    console.log("http======DocCode==>" + this.DocCode);
    this.getNumPages();
  },
  methods: {
    // # 计算pdf页码总数
    submit() {
      console.log("http======点击事件==>" + this.isSignature);

      if (this.isSignature == "ProjectEntrustedOnlineDoc") {
        //任命书文件签名
        this.AddCertificate("ProjectEntrustedOnlineDoc");
      } else if (this.isSignature == "SitePromiseRecordSign") {
        //承诺书文件签名
        this.AddCertificate("SitePromiseRecordSign");
      } else if (this.isSignature == "SiteSafeCostPlanMain") {
        //安全经费投入计划
        this.AddCertificate("SiteSafeCostPlanMain");
      } else if (this.isSignature == "ResponsibilityOrgPostUserDepositManage") {
        this.$router.push({
          name: "ProductionSafetySign",
          query: { DutyCode: this.DocCode },
        });
      } else {
        this.$router.push({
          path: "/GuidelineEntrustedRegPostDuty",
          query: {
            IDS: this.id,
            TypeName: this.$route.query.TypeName,
            isSignature: this.isSignature,
          },
        });
      }
    },
    getNumPages() {
      let loadingTask = pdf.createLoadingTask(this.url);
      loadingTask.promise
        .then((pdf) => {
          this.numPages = pdf.numPages;
        })
        .catch((err) => {
          console.error("pdf 加载失败", err);
        });
    },
    GuidelineRegCommonCompileGetSignInfo() {
      GuidelineRegCommonCompileGetSignInfo({ id: this.id }).then((res) => {
        this.imgUrl = res.data.MarkSignAttach;
        this.imgUrl2 = res.data.AuditSignAttach;
        this.imgUrl3 = res.data.ApproveSignAttach;
      });
    },
    GuidelineRegGetSignInfo() {
      GuidelineRegGetSignInfo({ id: this.id }).then((res) => {
        this.imgUrl = res.data.MarkSignAttach;
        this.imgUrl2 = res.data.AuditSignAttach;
        this.imgUrl3 = res.data.ApproveSignAttach;
      });
    },

    //控制弹窗是否显示
    AddCertificate(add) {
      this.adds = add;
      this.zIndex = 8;
      this.isCertificate = true;
      this.isCertificate2 = true;
      this.overwrite();
    },
    Canvas_goBack() {
      this.zIndex = -8;
      this.isCertificate = false;
      this.isCertificate2 = false;
    },
    //mobile
    touchStart(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clienX,
          y: ev.targetTouches[0].clientY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    touchMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    touchEnd(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (ev.touches.length == 1) {
        let obj = {
          x: ev.targetTouches[0].clientX - this.stageInfo.left,
          y: ev.targetTouches[0].clientY - this.stageInfo.top,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
      }
    },
    //pc
    mouseDown(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.startX = obj.x;
        this.startY = obj.y;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.isDown = true;
      }
    },
    mouseMove(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.moveY = obj.y;
        this.moveX = obj.x;
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.startY = obj.y;
        this.startX = obj.x;
        this.points.push(obj);
      }
    },
    mouseUp(ev) {
      ev = ev || event;
      ev.preventDefault();
      if (1) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY,
        };
        this.canvasTxt.beginPath();
        this.canvasTxt.moveTo(this.startX, this.startY);
        this.canvasTxt.lineTo(obj.x, obj.y);
        this.canvasTxt.stroke();
        this.canvasTxt.closePath();
        this.points.push(obj);
        this.points.push({ x: -1, y: -1 });
        this.isDown = false;
      }
    },
    //重写
    overwrite() {
      this.canvasTxt.clearRect(
        0,
        0,
        this.$refs.canvasF.width,
        this.$refs.canvasF.height
      );
      this.points = [];
    },
    // 上传图片
    afterRead(base64) {
      var params = {
        Img: base64,
      };
      CommonAttachUploadBase64(params)
        .then((res) => {
          this.Sign(res.data.FilePath);
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    //提交签名
    commit() {
      this.afterRead(this.$refs.canvasF.toDataURL());
    },

    Sign(url) {
      if (this.isSignature == "SitePromiseRecordSign") {
        var data = {
          SignPic: url,
          CompanyCode: this.CompanyCode,
          DocCode: this.DocCode,
          Code: this.DocCode,
        };

        SitePromiseRecordSign(data)
          .then((res) => {
            setTimeout(() => {
              // this.$router.push("/Site_Appointment");
              this.$router.ggoRefresh();
            }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      } else if (this.isSignature == "ProjectEntrustedOnlineDoc") {
        var data = {
          SignPic: url,
          CompanyCode: this.CompanyCode,
          DocCode: this.DocCode,
        };
        SiteAppointmentSign(data)
          .then((res) => {
            setTimeout(() => {
              // this.$router.push("/Site_Appointment");
              this.$router.goRefresh();
            }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      } else if (this.isSignature == "SiteSafeCostPlanMain") {
        var data = {
          SignPic: url,
          CompanyCode: this.CompanyCode,
          DocCode: this.DocCode,
          Code: this.DocCode,
        };

        SiteSafeCostPlanMainSign(data)
          .then((res) => {
            setTimeout(() => {
              // this.$router.push("/Site_Appointment");
              this.$router.goRefresh();
            }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },

    // SiteAppointmentSign(data).then.((res)
    //         =>{

    //         });
  },
};
</script>

<style lang="less" scoped>
.read-pdf {
  min-height: 100vh;
}

.button-fixed {
  position: fixed;
  bottom: 0px;
}
.popup2 {
  width: 100%;
  height: 100%;
  padding-top: 16px;
  padding-bottom: 16px;
  text-align: center;
  border-radius: 7px;
}
.user-info {
  min-height: 100vh;
  background-color: #fff;
}
.imgCanvas {
  /* background-color: #71b900; */
  border: 1px solid #7d7d7d;
  width: 50px;
  height: 50px;
}
.signatureBox-popup {
  opacity: 1;
  background: #666;
  display: none;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  padding-top: 200px;
}

.signatureBox {
  width: 100%;
  height: calc(100% - 50px);
  box-sizing: border-box;
  overflow: hidden;
  background: #fff;
  height: 60%;
  z-index: 8;
  display: inline-flex;
  flex-direction: column;
}
.canvasBox {
  box-sizing: border-box;
  flex: 1;
  height: 100%;
}
canvas {
  margin: 20px;
  width: 90%;
  /* height: 200px; */
  border: 1px solid #7d7d7d;
}
.btnBox {
  padding: 10px;
  text-align: center;
}
.btnBox button:first-of-type {
  background: transparent;
  border-radius: 4px;
  height: 40px;
  width: 80px;
  font-size: 14px;
}
.btnBox button:last-of-type {
  background: #71b900;
  color: #fff;
  border-radius: 4px;
  height: 40px;
  width: 80px;
  font-size: 14px;
}
</style>